import { defineStore } from 'pinia'
import { ref } from 'vue'
import { loginAPI } from '@/apis/user'
import { useCartStore } from '@/stores/cart'
import { mergeCartAPI } from '@/apis/cart'

export const useUserStore = defineStore('user', () => {
  const cartStore = useCartStore()
  // 定义管理用户数据的state
  const userInfo = ref({})

  // 定义获取接口数据的action函数
  const getUserInfo = async ({ account, password }) => {
    const { result } = await loginAPI({ account, password })
    userInfo.value = result

    // 合并购物车
    await mergeCartAPI(cartStore.cartList.map(v => {
      return {
        skuId: v.skuId,
        selected: v.selected,
        count: v.count
      }
    }))

    await cartStore.refreshCart()
  }

  const clearUserInfo = () => {
    userInfo.value = {}
    // 执行清空购物车
    cartStore.clearCart()
  }

  // 以对象的格式把state和action返回回去
  return {
    userInfo,
    getUserInfo,
    clearUserInfo
  }
}, { persist: true })
